<template>
  <div class="auth-container">
    <div class="container contentWrap">
      <div class="_left">
        <div class="login-top flex-align">
          <span class="login-top-language login-top-language-border">中文简体</span>
          <span class="login-top-language">English</span>
        </div>
        <div class="slogen">
          <h1>欢迎来到</h1>
          <h1>深圳马拉松</h1>
        </div>
      </div>

      <!-- 登录注册表单窗口 -->
      <div class="auth-form-wrapper">
        <div class="auth-form">
          <!-- 标签页切换 -->
          <div class="auth-tabs" v-if="activeTab !== 'forgot'">
            <div
              class="auth-tab"
              :class="{ active: activeTab === 'login' }"
              @click="activeTab = 'login'"
            >
              账号密码登录
            </div>
            <div
              class="auth-tab"
              :class="{ active: activeTab === 'register' }"
              @click="activeTab = 'register'"
            >
              账号注册
            </div>
          </div>

          <!-- 登录表单 -->
          <div v-if="activeTab === 'login'" class="form-content">
            <div class="form-group">
              <label>账号</label>
              <input
                type="text"
                v-model="loginForm.account"
                placeholder="请输入邮箱或手机号码"
                class="form-input"
              />
              <div v-if="loginForm.accountError" class="error-text">
                {{ loginForm.accountError }}
              </div>
            </div>

            <div class="form-group">
              <label>密码</label>
              <div class="password-input">
                <input
                  :type="showPassword ? 'text' : 'password'"
                  v-model="loginForm.password"
                  placeholder="请输入8～16位密码"
                  class="form-input"
                />
                <div v-if="loginForm.passwordError" class="error-text">
                  {{ loginForm.passwordError }}
                </div>
                <span class="password-toggle" @click="showPassword = !showPassword"> 👁 </span>
              </div>
              <div class="password-hint">
                密码必须包含大写字母、小写字母、特殊符号、数字中的三类
              </div>
            </div>

            <button class="auth-button" @click="handleLogin">登录</button>

            <div class="auth-links">
              <a href="#" class="forgot-password" @click="activeTab = 'forgot'">忘记密码？</a>
            </div>

            <div class="other-login">
              <div class="other-login-title">其他登录方式</div>
              <div class="other-login-icons">
                <ImageLoad filePath="bwx.png" class="titleIcon"></ImageLoad>
              </div>
            </div>
          </div>

          <!-- 注册表单 -->
          <div v-if="activeTab === 'register'" class="form-content">
            <div class="form-group">
              <label>账号</label>
              <input
                type="text"
                v-model="registerForm.account"
                placeholder="请输入邮箱/手机号码"
                class="form-input"
                :class="{ error: registerForm.accountError }"
              />
              <div v-if="registerForm.accountError" class="error-text">
                {{ registerForm.accountError }}
              </div>
            </div>

            <div class="form-group">
              <label>验证码</label>
              <div class="verification-input">
                <input
                  type="text"
                  v-model="registerForm.verificationCode"
                  placeholder="请输入验证码"
                  class="form-input verification-code"
                />
                <button
                  class="get-code-btn"
                  @click="getVerificationCode"
                  :disabled="codeCountdown > 0"
                >
                  {{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}
                </button>
              </div>
              <div v-if="registerForm.codeError" class="error-text">
                {{ registerForm.codeError }}
              </div>
            </div>

            <div class="form-group">
              <label>密码</label>
              <div class="password-input">
                <input
                  :type="showRegisterPassword ? 'text' : 'password'"
                  v-model="registerForm.password"
                  placeholder="请输入8～16位密码"
                  class="form-input"
                />
                <span class="password-toggle" @click="showRegisterPassword = !showRegisterPassword">
                  👁
                </span>
              </div>
              <div v-if="registerForm.passwordError" class="error-text">
                {{ registerForm.passwordError }}
              </div>
            </div>

            <div class="agreement">
              <label class="checkbox-label">
                <input type="checkbox" v-model="registerForm.agreeTerms" />
                <span class="checkmark"></span>
                我已阅读并同意《上马网用户注册协议》及《隐私政策》
              </label>
            </div>

            <button
              class="auth-button"
              @click="handleRegister"
              :disabled="!registerForm.agreeTerms"
            >
              确定
            </button>

            <div class="auth-links">
              <span>已有账号，</span>
              <a href="#" @click="activeTab = 'login'">请登录</a>
            </div>
          </div>

          <!-- 忘记密码表单 -->
          <div v-if="activeTab === 'forgot'" class="form-content">
            <div class="forgot-header">
              <h3>找回密码</h3>
            </div>

            <div class="form-group">
              <label>账号</label>
              <input
                type="text"
                v-model="forgotForm.account"
                placeholder="请输入邮箱或手机号码"
                class="form-input"
                :class="{ error: forgotForm.accountError }"
              />
              <div v-if="forgotForm.accountError" class="error-text">
                {{ forgotForm.accountError }}
              </div>
            </div>

            <div class="form-group">
              <label>图形验证码</label>
              <div class="captcha-input">
                <input
                  type="text"
                  v-model="forgotForm.captcha"
                  placeholder="请输入图形验证码"
                  class="form-input captcha-code"
                  :class="{ error: forgotForm.captchaError }"
                />
                <div class="captcha-image" @click="refreshCaptcha">
                  <canvas ref="captchaCanvas" width="100" height="40"></canvas>
                  <span class="refresh-text">刷新</span>
                </div>
              </div>
              <div v-if="forgotForm.captchaError" class="error-text">
                {{ forgotForm.captchaError }}
              </div>
            </div>

            <div class="form-group">
              <label>验证码</label>
              <div class="verification-input">
                <input
                  type="text"
                  v-model="forgotForm.verificationCode"
                  placeholder="请输入验证码"
                  class="form-input verification-code"
                  :class="{ error: forgotForm.codeError }"
                />
                <button
                  class="get-code-btn"
                  @click="getForgotVerificationCode"
                  :disabled="forgotCodeCountdown > 0"
                >
                  {{ forgotCodeCountdown > 0 ? `${forgotCodeCountdown}s` : '获取验证码' }}
                </button>
              </div>
              <div v-if="forgotForm.codeError" class="error-text">
                {{ forgotForm.codeError }}
              </div>
            </div>

            <div class="form-group">
              <label>密码</label>
              <div class="password-input">
                <input
                  :type="showForgotPassword ? 'text' : 'password'"
                  v-model="forgotForm.password"
                  placeholder="请输入8～16位密码"
                  class="form-input"
                  :class="{ error: forgotForm.passwordError }"
                />
                <span class="password-toggle" @click="showForgotPassword = !showForgotPassword">
                  👁
                </span>
              </div>
              <div v-if="forgotForm.passwordError" class="error-text">
                {{ forgotForm.passwordError }}
              </div>
            </div>

            <button class="auth-button" @click="handleForgotPassword">确定</button>

            <div class="auth-links">
              <span>已有账号，</span>
              <a href="#" @click="activeTab = 'login'">请登录</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ImageLoad from '@/components/common/ImageLoad/index.vue'
import { getPhoneCode, register, sendCode, SignIn } from '@/api/common.js'
import { $message } from '@/utils/message.js'
import { validateEmailOrPhone, isEmail, isPhone } from '@/utils/validator'
import { useUserStore } from '@/stores/user'

// 路由和状态管理
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeTab = ref('login') // 'login', 'register', 'forgot'
const showPassword = ref(false)
const showRegisterPassword = ref(false)
const showForgotPassword = ref(false)
const codeCountdown = ref(0)
const forgotCodeCountdown = ref(0)
const captchaText = ref('') // 图形验证码文本
const captchaCanvas = ref(null)

// 表单数据
const loginForm = reactive({
  account: '',
  password: '',
  accountError: '',
  passwordError: ''
})

const registerForm = reactive({
  account: '',
  verificationCode: '',
  password: '',
  agreeTerms: false,
  accountError: '',
  codeError: '',
  passwordError: ''
})

const forgotForm = reactive({
  account: '',
  captcha: '',
  verificationCode: '',
  password: '',
  accountError: '',
  captchaError: '',
  codeError: '',
  passwordError: ''
})

// 生成图形验证码
const generateCaptcha = () => {
  const canvas = captchaCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
  let captcha = ''

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 设置背景
  ctx.fillStyle = '#f0f0f0'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 生成验证码文本
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  captchaText.value = captcha

  // 绘制验证码
  ctx.font = '20px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'

  for (let i = 0; i < captcha.length; i++) {
    ctx.fillStyle = `hsl(${Math.random() * 360}, 70%, 50%)`
    ctx.save()
    ctx.translate(25 * i + 12, 20)
    ctx.rotate((Math.random() - 0.5) * 0.5)
    ctx.fillText(captcha[i], 0, 0)
    ctx.restore()
  }

  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `hsl(${Math.random() * 360}, 70%, 50%)`
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha()
  forgotForm.captcha = ''
}

// 登录处理
const handleLogin = async () => {
  // 重置错误信息
  loginForm.accountError = ''
  loginForm.passwordError = ''

  if (!loginForm.account) {
    loginForm.accountError = '请输入账号'
    return
  }
  if (!loginForm.password) {
    loginForm.passwordError = '请输入密码'
    return
  }

  try {
    const params = {
      mobile: loginForm.account,
      password: loginForm.password
    }

    const res = await SignIn(params)
    if (res.code == 200 && res.data.token) {
      $message.success('登录成功')
      const token = res.data.token
      userStore.setIsSign(true)
      userStore.setToken(token)
      setTimeout(() => {
        router.replace('/')
        userStore.getUserInfo()
      }, 500)
    } else {
      $message.error(res.msg || '登录失败')
    }
  } catch (err) {
    console.error('登录错误:', err)
    $message.error('登录失败，请重试')
  }
}

// 注册处理
const handleRegister = async () => {
  validateRegisterForm()

  if (
    registerForm.accountError ||
    registerForm.codeError ||
    registerForm.passwordError
  ) {
    return
  }

  if (!registerForm.agreeTerms) {
    $message.error('请同意用户协议')
    return
  }

  try {
    const params = {
      mobile: registerForm.account,
      code: registerForm.verificationCode,
      password: registerForm.password,
      type: isEmail(registerForm.account) ? 1 : 0
    }

    const res = await register(params)
    if (res.code === 200) {
      $message.success('注册成功！')
      activeTab.value = 'login'
    } else {
      $message.error(`注册失败！${res.message}`)
    }
  } catch (err) {
    console.error('注册错误:', err)
    $message.error('注册失败，请重试')
  }
}

// 处理忘记密码
const handleForgotPassword = () => {
  validateForgotForm()

  if (
    forgotForm.accountError ||
    forgotForm.captchaError ||
    forgotForm.codeError ||
    forgotForm.passwordError
  ) {
    return
  }

  // 调用忘记密码API
  const params = {
    account: forgotForm.account,
    captcha: forgotForm.captcha,
    code: forgotForm.verificationCode,
    password: forgotForm.password
  }

  // 这里调用重置密码API
  console.log('重置密码参数:', params)
  $message.success('密码重置成功！')
  activeTab.value = 'login'
}

// 验证忘记密码表单
const validateForgotForm = () => {
  // 验证账号
  const regexResult = validateEmailOrPhone(forgotForm.account)
  if (regexResult.valid) {
    forgotForm.accountError = ''
  } else {
    forgotForm.accountError = regexResult.message
  }

  // 验证图形验证码
  if (!forgotForm.captcha) {
    forgotForm.captchaError = '请输入图形验证码'
  } else if (forgotForm.captcha.toLowerCase() !== captchaText.value.toLowerCase()) {
    forgotForm.captchaError = '图形验证码错误'
  } else {
    forgotForm.captchaError = ''
  }

  // 验证验证码
  if (!forgotForm.verificationCode) {
    forgotForm.codeError = '请输入验证码'
  } else {
    forgotForm.codeError = ''
  }

  // 验证密码
  if (!forgotForm.password) {
    forgotForm.passwordError = '请输入密码'
  } else if (forgotForm.password.length < 8 || forgotForm.password.length > 16) {
    forgotForm.passwordError = '密码长度应为8-16位'
  } else {
    forgotForm.passwordError = ''
  }
}

// 验证注册表单
const validateRegisterForm = () => {
  // 验证手机号
  const regexResult = validateEmailOrPhone(registerForm.account)
  if (regexResult.valid) {
    registerForm.accountError = ''
  } else {
    registerForm.accountError = regexResult.message
  }

  // 验证验证码
  if (!registerForm.verificationCode) {
    registerForm.codeError = '请输入验证码'
  } else {
    registerForm.codeError = ''
  }

  // 验证密码
  if (!registerForm.password) {
    registerForm.passwordError = '请输入密码'
  } else if (registerForm.password.length < 8 || registerForm.password.length > 16) {
    registerForm.passwordError = '密码长度应为8-16位'
  } else {
    registerForm.passwordError = ''
  }
}

// 开始倒计时
const startCountDown = () => {
  codeCountdown.value = 60
  const timer = setInterval(() => {
    codeCountdown.value--
    if (codeCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 忘记密码验证码倒计时
const startForgotCountDown = () => {
  forgotCodeCountdown.value = 60
  const timer = setInterval(() => {
    forgotCodeCountdown.value--
    if (forgotCodeCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 获取验证码
const getVerificationCode = async () => {
  const regexResult = validateEmailOrPhone(registerForm.account)
  if (regexResult.valid) {
    registerForm.accountError = ''
    const params = {
      mobile: registerForm.account,
      type: isEmail(registerForm.account) ? 1 : 0,
    }
    try {
      const res = await sendCode(params)
      if (res.code == 200) {
        startCountDown()
        $message.success('验证码发送成功！')
      } else {
        $message.error(res.message || '验证码发送失败')
      }
    } catch (err) {
      console.error('获取验证码错误:', err)
      $message.error('验证码发送失败，请重试')
    }
  } else {
    registerForm.accountError = regexResult.message
  }
}

// 获取忘记密码验证码
const getForgotVerificationCode = async () => {
  // 先验证图形验证码
  if (!forgotForm.captcha) {
    forgotForm.captchaError = '请输入图形验证码'
    return
  }
  if (forgotForm.captcha.toLowerCase() !== captchaText.value.toLowerCase()) {
    forgotForm.captchaError = '图形验证码错误'
    return
  }
  forgotForm.captchaError = ''

  const regexResult = validateEmailOrPhone(forgotForm.account)
  if (regexResult.valid) {
    forgotForm.accountError = ''
    try {
      const res = await getPhoneCode(forgotForm.account)
      if (res.code == 200) {
        startForgotCountDown()
        $message.success('验证码发送成功！')
      } else {
        $message.error(res.message || '验证码发送失败')
      }
    } catch (err) {
      console.error('获取验证码错误:', err)
      $message.error('验证码发送失败，请重试')
    }
  } else {
    forgotForm.accountError = regexResult.message
  }
}

// 组件挂载时生成验证码
onMounted(() => {
  generateCaptcha()
})
</script>

<style lang="scss" scoped>
.forgot-header {
  text-align: center;
  margin-bottom: 30px;

  h3 {
    color: #333;
    font-size: 20px;
    font-weight: 600;
    margin: 0;
  }
}

.captcha-input {
  display: flex;
  gap: 10px;
  align-items: center;

  .captcha-code {
    flex: 1;
  }

  .captcha-image {
    position: relative;
    cursor: pointer;
    border: 1px solid #ddd;
    border-radius: 6px;
    overflow: hidden;

    canvas {
      display: block;
    }

    .refresh-text {
      position: absolute;
      bottom: 2px;
      right: 2px;
      font-size: 10px;
      color: #666;
      background: rgba(255, 255, 255, 0.8);
      padding: 1px 3px;
      border-radius: 2px;
    }

    &:hover {
      border-color: #e74c3c;

      .refresh-text {
        color: #e74c3c;
      }
    }
  }
}

.auth-container {
  position: relative;
  height: 100vh;
  background: url('../../../public/images/login_bg.jpg') center no-repeat;
  background-size: 100% 100%;
  z-index: 0;
  display: flex;
  flex-direction: column;
}

.contentWrap {
  display: flex;
  justify-content: space-between;
  margin-top: 60px;
  ._left {
    display: flex;
    flex-direction: column;
    align-items: start;
    .slogen {
      margin-top: 60px;
      h1 {
        color: #fff;
        font-size: 100px;
        font-family: Arial, Helvetica, sans-serif;
        line-height: 1.5;
      }
    }
  }
}

.login-top {
  display: flex;
  align-items: center;
  .login-top-language {
    font-size: 2.40734vh;
    color: #fff;
    line-height: 3.42583vh;
    padding: 0 3.51842vh;
    cursor: pointer;
    &:first-child {
      padding-left: 0;
    }
    white-space: nowrap;
  }
  .login-top-language-border {
    position: relative;
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      right: 0;
      width: 2px;
      height: 20px;
      background-color: #ffffff;
      transform: translateY(-50%);
    }
  }
}

.auth-form-wrapper {
  width: 5.41rem;
  background: #ffffff;
  z-index: 10;
  min-width: 500px;
}

.auth-form {
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 40px;
  width: 100%;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.auth-tabs {
  display: flex;
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
}

.auth-tab {
  flex: 1;
  padding: 15px 0;
  text-align: center;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;

  &.active {
    color: #e74c3c;
    border-bottom-color: #e74c3c;
  }

  &:hover {
    color: #e74c3c;
  }
}

.form-content {
  .form-group {
    margin-bottom: 20px;

    label {
      display: block;
      margin-bottom: 8px;
      font-size: 14px;
      font-weight: 500;
      color: #333;
    }
  }
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  box-sizing: border-box;

  &:focus {
    outline: none;
    border-color: #e74c3c;
  }

  &.error {
    border-color: #e74c3c;
  }

  &::placeholder {
    color: #999;
  }
}

.password-input {
  position: relative;

  .password-toggle {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    font-size: 16px;
    color: #999;
    user-select: none;
  }
}

.password-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}

.verification-input {
  display: flex;
  gap: 10px;

  .verification-code {
    flex: 1;
  }

  .get-code-btn {
    padding: 12px 16px;
    background: #e74c3c;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    white-space: nowrap;
    transition: background-color 0.3s ease;

    &:hover:not(:disabled) {
      background: #c0392b;
    }

    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
}

.error-text {
  margin-top: 5px;
  font-size: 12px;
  color: #e74c3c;
}

.agreement {
  margin-bottom: 20px;
  .login-icon wechat {
    display: flex;
    align-items: flex-start;
    cursor: pointer;
    font-size: 12px;
    color: #666;
    line-height: 1.4;

    input[type='checkbox'] {
      margin-right: 8px;
      margin-top: 2px;
    }
  }
  .checkbox-label {
    display: flex;
    align-items: center;
    font-size: 12px;
    gap: 5px;
  }
}

.auth-button {
  width: 100%;
  padding: 14px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-bottom: 20px;

  &:hover:not(:disabled) {
    background: #c0392b;
  }

  &:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
}

.auth-links {
  text-align: center;
  font-size: 14px;
  color: #666;

  a {
    color: #e74c3c;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  .forgot-password {
    color: #999;
  }
}

.other-login {
  margin-top: 30px;
  text-align: center;

  .other-login-title {
    font-size: 14px;
    color: #999;
    margin-bottom: 15px;
  }

  .other-login-icons {
    display: flex;
    justify-content: center;
    gap: 15px;
    img {
      width: 40px;
      height: 40px;
    }
  }

  .login-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    color: white;
    transition: transform 0.3s ease;

    &.wechat {
      background: #1aad19;
    }

    &:hover {
      transform: scale(1.1);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .auth-form {
    margin: 20px;
    padding: 30px 20px;
  }
}
</style>
